package com.ruoyi.asms.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.asms.domain.AsmsOwnMaintenanceDept;
import com.ruoyi.asms.domain.vo.AsmsOwnMaintenanceDeptAddVo;
import com.ruoyi.asms.domain.vo.AsmsOwnMaintenanceDeptEditVo;
import com.ruoyi.asms.domain.vo.AsmsOwnMaintenanceDeptVo;
import com.ruoyi.asms.service.IAsmsOwnMaintenanceDeptService;
import com.ruoyi.common.core.domain.KeyValueVo;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.SecurityUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.bean.BeanUtils;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.security.annotation.PreAuthorize;
import com.ruoyi.security.service.TokensService;
import com.ruoyi.system.controller.SysDeptController;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;

/**
 * 资产设备所有方和资产维护部门信息Controller
 *
 * @author yfkj
 * @date 2021-10-21
 */
@RestController
@RequestMapping("/asms/AsmsOwnMaintenanceDept")
public class AsmsOwnMaintenanceDeptController extends BaseController {
    @Autowired
    private IAsmsOwnMaintenanceDeptService asmsOwnMaintenanceDeptService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private TokensService tokenService;
//    @Autowired
//    private RemoteDeptService remoteDeptService;
    @Autowired
    private SysDeptController deptController;

    /**
     * 查询资产设备所有方和资产维护部门信息列表
     */
    //@PreAuthorize
    //@PreAuthorize(hasPermi = "asms:AsmsOwnMaintenanceDept:list")
    @GetMapping("/list")
    @ApiOperation("查询资产设备所有方和资产维护部门信息列表，可通过部门名称查询")
    public TableDataInfo list(@ApiParam(name = "deptName", value = "部门名称") String deptName,
                              @ApiParam(name = "type", value = "1：资产所有方查询售后维护方列表\n" +
                                      "2：售后维护方查看资产所有方列表", required = true) Integer type) {
        LoginUser loginUser = tokenService.getLoginUser();
        List<AsmsOwnMaintenanceDeptVo> vos = new ArrayList<>();

        //用户可看见所有可见部门的维护商
        for (Long deptId : loginUser.getDeptIds()) {
            R<SysDept> oDeptInfo = deptController.getDeptById(deptId);
            if (R.FAIL == oDeptInfo.getCode()) {
                throw new ServiceException(oDeptInfo.getMsg());
            }

            List<AsmsOwnMaintenanceDept> list;
            if (type == 1) {
                startPage();
                list = asmsOwnMaintenanceDeptService.list(new QueryWrapper<AsmsOwnMaintenanceDept>()
                        .eq(AsmsOwnMaintenanceDept.OWN_DEPT_ID, deptId).orderByDesc(AsmsOwnMaintenanceDept.CREATE_TIME));
            } else {
                startPage();
                list = asmsOwnMaintenanceDeptService.list(new QueryWrapper<AsmsOwnMaintenanceDept>()
                        .eq(AsmsOwnMaintenanceDept.MAINTENANCE_DEPT_ID, deptId).orderByDesc(AsmsOwnMaintenanceDept.CREATE_TIME));
            }

            for (AsmsOwnMaintenanceDept asmsOwnMaintenanceDept : list) {
                //获取维护部门
                R<SysDept> mDeptInfo = deptController.getDeptById(asmsOwnMaintenanceDept.getMaintenanceDeptId());
                if (R.FAIL == mDeptInfo.getCode()) {
                    throw new ServiceException(mDeptInfo.getMsg());
                }
                //获取所有方部门
                R<SysDept> ownDept = deptController.getDeptById(asmsOwnMaintenanceDept.getOwnDeptId());
                if (ownDept.getCode() == R.FAIL) {
                    throw new ServiceException(ownDept.getMsg());
                }
                if (StringUtils.isNotEmpty(deptName) && !oDeptInfo.getData().getDeptShortName().contains(deptName)
                        && !mDeptInfo.getData().getDeptShortName().contains(deptName)) {
                    continue;
                }
                AsmsOwnMaintenanceDeptVo vo = new AsmsOwnMaintenanceDeptVo();
                BeanUtils.copyProperties(asmsOwnMaintenanceDept, vo);

                vo.setOwnDeptFullName(ownDept.getData().getDeptFullName());
                vo.setOwnDeptShortName(ownDept.getData().getDeptShortName());
                vo.setOwnLeader(ownDept.getData().getLeader());
                vo.setOwnLogo(ownDept.getData().getLogo());
                vo.setOwnPhone(ownDept.getData().getPhone());
                vo.setOwnEmail(ownDept.getData().getEmail());

                vo.setMDeptFullName(mDeptInfo.getData().getDeptFullName());
                vo.setMDeptShortName(mDeptInfo.getData().getDeptShortName());
                vo.setMLeader(mDeptInfo.getData().getLeader());
                vo.setMLogo(mDeptInfo.getData().getLogo());
                vo.setMPhone(mDeptInfo.getData().getPhone());
                vo.setMEmail(mDeptInfo.getData().getEmail());

                vos.add(vo);
            }
        }
        //按记录创建时间降序
        vos.sort(Comparator.comparing(AsmsOwnMaintenanceDeptVo::getCreateBy));
        return getDataTable(vos);
    }

    @GetMapping(value ="/exportAllDept", produces = "application/octet-stream")
    public void exportAllDept(HttpServletResponse response,@ApiParam(name = "deptName", value = "部门名称") String deptName,
                              @ApiParam(name = "type", value = "1：资产所有方查询售后维护方列表\n" +
                                      "2：售后维护方查看资产所有方列表", required = true) Integer type) throws IOException {
        LoginUser loginUser = tokenService.getLoginUser();
        List<AsmsOwnMaintenanceDeptVo> vos = new ArrayList<>();

        //用户可看见所有可见部门的维护商
        for (Long deptId : loginUser.getDeptIds()) {
            R<SysDept> oDeptInfo = deptController.getDeptById(deptId);
            if (R.FAIL == oDeptInfo.getCode()) {
                throw new ServiceException(oDeptInfo.getMsg());
            }
            List<AsmsOwnMaintenanceDept> list = null;
            if (type == 1) {
                list = asmsOwnMaintenanceDeptService.list(new QueryWrapper<AsmsOwnMaintenanceDept>()
                        .eq(AsmsOwnMaintenanceDept.OWN_DEPT_ID, deptId).orderByDesc(AsmsOwnMaintenanceDept.CREATE_TIME));
            } else {
                list = asmsOwnMaintenanceDeptService.list(new QueryWrapper<AsmsOwnMaintenanceDept>()
                        .eq(AsmsOwnMaintenanceDept.MAINTENANCE_DEPT_ID, deptId).orderByDesc(AsmsOwnMaintenanceDept.CREATE_TIME));
            }

            for (AsmsOwnMaintenanceDept asmsOwnMaintenanceDept : list) {
                //获取维护部门
                R<SysDept> mDeptInfo = deptController.getDeptById(asmsOwnMaintenanceDept.getMaintenanceDeptId());
                if (R.FAIL == mDeptInfo.getCode()) {
                    throw new ServiceException(mDeptInfo.getMsg());
                }
                //获取所有方部门
                R<SysDept> ownDept = deptController.getDeptById(asmsOwnMaintenanceDept.getOwnDeptId());
                if (ownDept.getCode() == R.FAIL) {
                    throw new ServiceException(ownDept.getMsg());
                }
                if (StringUtils.isNotEmpty(deptName) && !oDeptInfo.getData().getDeptShortName().contains(deptName)
                        && !mDeptInfo.getData().getDeptShortName().contains(deptName)) {
                    continue;
                }
                AsmsOwnMaintenanceDeptVo vo = new AsmsOwnMaintenanceDeptVo();
                BeanUtils.copyProperties(asmsOwnMaintenanceDept, vo);

                vo.setOwnDeptFullName(ownDept.getData().getDeptFullName());
                vo.setOwnDeptShortName(ownDept.getData().getDeptShortName());
                vo.setOwnLeader(ownDept.getData().getLeader());
                vo.setOwnLogo(ownDept.getData().getLogo());
                vo.setOwnPhone(ownDept.getData().getPhone());
                vo.setOwnEmail(ownDept.getData().getEmail());

                vo.setMDeptFullName(mDeptInfo.getData().getDeptFullName());
                vo.setMDeptShortName(mDeptInfo.getData().getDeptShortName());
                vo.setMLeader(mDeptInfo.getData().getLeader());
                vo.setMLogo(mDeptInfo.getData().getLogo());
                vo.setMPhone(mDeptInfo.getData().getPhone());
                vo.setMEmail(mDeptInfo.getData().getEmail());
                vo.setCreateTimeStr(DateUtils.parseLongToStr(DateUtils.YYYY_MM_DD,vo.getCreateTime()));
                vos.add(vo);
            }
        }
        //按记录创建时间降序
        vos.sort(Comparator.comparing(AsmsOwnMaintenanceDeptVo::getCreateBy));

        ExcelUtil<AsmsOwnMaintenanceDeptVo> util = new ExcelUtil<AsmsOwnMaintenanceDeptVo>(AsmsOwnMaintenanceDeptVo.class);


        util.exportExcel(response, vos, "维护客户");
    }
    @PreAuthorize
    @GetMapping("/getMDeptById")
    @ApiOperation("根据资产所有方id获取资产维护方下拉列表")
    public R<List<KeyValueVo>> getMDeptById(@RequestParam("ownDeptId") Long ownDeptId){
        List<AsmsOwnMaintenanceDept> mDeptList = asmsOwnMaintenanceDeptService.list(new QueryWrapper<AsmsOwnMaintenanceDept>()
                .eq(AsmsOwnMaintenanceDept.OWN_DEPT_ID, ownDeptId));
        HashSet<Long> MDeptIds = new HashSet<>();
        for (AsmsOwnMaintenanceDept dept : mDeptList) {
            MDeptIds.add(dept.getMaintenanceDeptId());
        }
        if (MDeptIds.size() == 0) {
            return R.fail("当前部门没有资产维护方！");
        }
        R<List<SysDept>> MDeptList = deptController.getDeptListByIds(MDeptIds);
        if (MDeptList.getCode() == R.FAIL) {
            throw new ServiceException(MDeptList.getMsg());
        }
        ArrayList<KeyValueVo> mDeptVos = new ArrayList<>();
        for (SysDept dept : MDeptList.getData()) {
            KeyValueVo vo = new KeyValueVo();
            vo.setKey(dept.getDeptId());
            vo.setValue(dept.getDeptShortName());
            mDeptVos.add(vo);
        }
        return R.ok(mDeptVos);
    }

    /**
     * 导出资产设备所有方和资产维护部门信息列表
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "asms:AsmsOwnMaintenanceDept:export")
    @Log(title = "资产设备所有方和资产维护部门信息", businessType = BusinessType.EXPORT)
    @PostMapping(value="/export", produces = "application/octet-stream")
    public void export(HttpServletResponse response, AsmsOwnMaintenanceDept asmsOwnMaintenanceDept) throws IOException {
        List<AsmsOwnMaintenanceDept> list = asmsOwnMaintenanceDeptService.selectAsmsOwnMaintenanceDeptList(asmsOwnMaintenanceDept);
        ExcelUtil<AsmsOwnMaintenanceDept> util = new ExcelUtil<AsmsOwnMaintenanceDept>(AsmsOwnMaintenanceDept.class);
        util.exportExcel(response, list, "资产设备所有方和资产维护部门信息数据");
    }

    /**
     * 获取资产设备所有方和资产维护部门信息详细信息
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "asms:AsmsOwnMaintenanceDept:query")
    @GetMapping(value = "/{assetOwnMaintenanceDeptId}")
    public AjaxResult getInfo(@PathVariable("assetOwnMaintenanceDeptId") Long assetOwnMaintenanceDeptId) {
        return AjaxResult.success(asmsOwnMaintenanceDeptService.selectAsmsOwnMaintenanceDeptByAssetOwnMaintenanceDeptId(assetOwnMaintenanceDeptId));
    }

    /**
     * 新增资产设备所有方和资产维护部门信息
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "asms:AsmsOwnMaintenanceDept:add")
    @Log(title = "资产设备所有方和资产维护部门信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ApiOperation("添加记录")
    public AjaxResult add(@RequestBody AsmsOwnMaintenanceDeptAddVo vo) {
        SysDept sysDept = new SysDept();
        BeanUtils.copyProperties(vo, sysDept);
        sysDept.setDeptType(vo.getFlag() == 1 ? "1" : "2");
        R<SysDept> deptR = deptController.add(sysDept);
        AsmsOwnMaintenanceDept asmsOwnMaintenanceDept = new AsmsOwnMaintenanceDept();
        if (vo.getFlag() == 1) {
            //新增资产维护方
            asmsOwnMaintenanceDept.setOwnDeptId(SecurityUtils.getDeptId());
            asmsOwnMaintenanceDept.setMaintenanceDeptId(deptR.getData().getDeptId());
            asmsOwnMaintenanceDept.setCreateBy(SecurityUtils.getUsername());
            asmsOwnMaintenanceDept.setCreateTime(System.currentTimeMillis());
        } else if (vo.getFlag() == 2) {
            //新增资产所有方
            asmsOwnMaintenanceDept.setMaintenanceDeptId(SecurityUtils.getDeptId());
            asmsOwnMaintenanceDept.setOwnDeptId(deptR.getData().getDeptId());
            asmsOwnMaintenanceDept.setCreateBy(SecurityUtils.getUsername());
            asmsOwnMaintenanceDept.setCreateTime(System.currentTimeMillis());
        }
        return toAjax(asmsOwnMaintenanceDeptService.insertAsmsOwnMaintenanceDept(asmsOwnMaintenanceDept));
    }

    /**
     * 修改资产设备所有方和资产维护部门信息
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "asms:AsmsOwnMaintenanceDept:edit")
    @Log(title = "资产设备所有方和资产维护部门信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ApiOperation("修改记录")
    public AjaxResult edit(@RequestBody AsmsOwnMaintenanceDeptEditVo vo) {
        SysDept dept = new SysDept();
        BeanUtils.copyProperties(vo, dept);
        deptController.edit(dept);
        return AjaxResult.success("修改成功！");
    }

    /**
     * 删除资产设备所有方和资产维护部门信息
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "asms:AsmsOwnMaintenanceDept:remove")
    @Log(title = "资产设备所有方和资产维护部门信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{assetOwnMaintenanceDeptIds}")
    public AjaxResult remove(@PathVariable Long[] assetOwnMaintenanceDeptIds) {
        return toAjax(asmsOwnMaintenanceDeptService.deleteAsmsOwnMaintenanceDeptByAssetOwnMaintenanceDeptIds(assetOwnMaintenanceDeptIds));
    }

    @GetMapping("/getMDeptIdsByODeptId")
    public R<HashSet<Long>> getMDeptIdsByODeptId(@RequestParam("deptId") Long deptId) {
        HashSet<Long> deptIds = new HashSet<>();
        List<AsmsOwnMaintenanceDept> deptList = asmsOwnMaintenanceDeptService.list(new QueryWrapper<AsmsOwnMaintenanceDept>()
                .eq(AsmsOwnMaintenanceDept.OWN_DEPT_ID, deptId));
        deptList.forEach(item -> deptIds.add(item.getMaintenanceDeptId()));
        return R.ok(deptIds);
    }

    /**
     * 获取某个部门维护的所有客户的ID（用于远程调用）
     * @return
     */
    @GetMapping("/getODeptIdsByMDeptId")
    public R<HashSet<Long>> getODeptIdsByMDeptId(@RequestParam("mDeptId") Long mDeptId) {
        HashSet<Long> deptIds = new HashSet<>();
        List<AsmsOwnMaintenanceDept> deptList = asmsOwnMaintenanceDeptService.list(new QueryWrapper<AsmsOwnMaintenanceDept>()
                .eq(AsmsOwnMaintenanceDept.MAINTENANCE_DEPT_ID, mDeptId));
        deptList.forEach(item -> deptIds.add(item.getOwnDeptId()));
        return R.ok(deptIds);
    }
}
